package pe.com.certicom.scv.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Hashcipher {
	
	private static final char [] hexchars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
	
	public static String hashString(String sPassword) {
		if (sPassword == null || sPassword.equals("")) {
			return "empty:";
		} else {
			try {
				MessageDigest md = MessageDigest.getInstance("SHA-1");
				md.update(sPassword.getBytes("UTF-8"));
				byte[] res = md.digest();
				return "sha1:" + byte2hex(res);
			} catch (NoSuchAlgorithmException e) {
				return "plain:" + sPassword;
			} catch (UnsupportedEncodingException e) {
				return "plain:" + sPassword;
			}
		}
	}
	
	public static String getPasswordAleatorio(int n) {
        char[] pw = new char[n];
        int c = 'A';
        int r1 = 0;
        for (int i = 0; i < n; i++) {
            r1 = (int) (Math.random() * 3);
            switch (r1) {
                case 0:
                    c = '0' + (int) (Math.random() * 10);
                    break;
                case 1:
                    c = 'a' + (int) (Math.random() * 26);
                    break;
                case 2:
                    c = 'A' + (int) (Math.random() * 26);
                    break;
            }
            pw[i] = (char) c;
        }
        return new String(pw);
    }
	
	public static void main(String... s ){
		System.out.println("P2:\t"+hashString("123"));
		System.out.println("P3:\t"+hashString("123"));
	}

	public static String byte2hex(byte[] binput) {

		StringBuffer sb = new StringBuffer(binput.length * 2);
		for (int i = 0; i < binput.length; i++) {
			int high = ((binput[i] & 0xF0) >> 4);
			int low = (binput[i] & 0x0F);
			sb.append(hexchars[high]);
			sb.append(hexchars[low]);
		}
		return sb.toString();
	}
}
